package lion.blog.tag;

import java.io.IOException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.apache.commons.lang.StringUtils;

import lion.blog.model.BlogCatelog;
import lion.blog.service.BlogService;
import lion.blog.util.BlogUtil;
import lion.dev.lang.MapJ;
import lion.framework.core.bean.BeanFactory;
import lion.framework.core.db.SessionFactory;
import lombok.Setter;

/**
 * 
 * 文章归档
 * 
 * @author lion
 * @email hl_0074@sina.com
 * @date 2015年12月2日
 */
// TODO 完成归档的标签
public class ArticleArchiveTag extends BodyTagSupport {

	private static final long serialVersionUID = 1L;

	@Setter
	private String catelog;

	private List<MapJ> rows;

	@Override
	public int doStartTag() throws JspException {

		StringBuilder sql = new StringBuilder();
		sql.append("select id,title,publishTime from BlogArticle ");
		BlogService service = BeanFactory.getBeanFactory(BeanFactory.PLATFORM_BEAN_FACTORY).get("blog.BlogService");
		MapJ param = new MapJ();
		if (StringUtils.isNotBlank(this.catelog)) {
			BlogCatelog catelog = service.getBlogCatelog(this.catelog);
			if (catelog != null) {
				sql.append(" where catelog=:catelog");
				param.put("catelog", catelog.getId());
			}
		}
		sql.append(" order by publishTime desc");

		rows = SessionFactory.getCurrentDB().query(sql.toString(), param).getRows();
		return super.doStartTag();
	}

	@Override
	public int doEndTag() throws JspException {

		if (this.rows.isEmpty()) { return EVAL_PAGE; }

		StringBuilder builder = new StringBuilder();
		int year = 0, month = -1;
		builder.append("<div class=\"archive_list\">");
		for (MapJ ar : this.rows) {
			Date publishTime = ar.getDate("publishTime");
			LocalDate ld = publishTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
			int y = ld.getYear();
			int m = ld.getMonthValue();
			if (y != year) {
				if (year > 0) {
					builder.append("</div>");
				}
				year = y;
				builder.append("<div><h3 class=\"archive_year\">" + year + "年</h3><ul>");
			}
			if (m != month) {
				if (month > 0) {
					builder.append("</ul></li>");
				}
				month = m;
				builder.append("<li><b>" + month + "月</b><ul>");

			}
			builder.append("<li><span>" + ld.getDayOfMonth() + "日</span> <a href=\"" + BlogUtil.getBlogLink(ar, null) + "\">" + ar.getString("title") + "</a></li>");
		}
		builder.append("</ul></li></ul></div></div>");
		try {
			this.pageContext.getOut().append(builder.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}

		return super.doEndTag();
	}

}
